//
//  HMComposeViewController.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/26.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit
import SVProgressHUD

/*
 当控制器在一个导航控制器里面,控制器的view或第一个子view是可以滚动的,那么他会帮我们自动往下滚动64
 如果不想让他来滚动可以设置控制器的 automaticallyAdjustsScrollViewInsets
 */

class HMComposeViewController: UIViewController {
    // 最长的文字数量
    fileprivate let maxOfStatusLength = 25
    
    @IBOutlet weak var textView: HMPlaceholderTextView!
    
    /// 图片选择器的底部约束
    private var photoSelectorBottomCons: NSLayoutConstraint?

    @IBOutlet weak var lengthTipLabel: UILabel!
    @IBOutlet weak var toolBar: UIToolbar!
    
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.automaticallyAdjustsScrollViewInsets = false

        setupNavigationBar()
//        textView.placehodlerLabel.text = "分享新鲜事..."
        textView.placeholder = "分享新鲜事..."
        textView.delegate = self
        
        setupPhotoSelector()
        setupToolBar()
        
        // 监听键盘的弹出
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(nofitication:)), name: .UIKeyboardWillChangeFrame, object: nil)
        
        // 主动弹出键盘
//        self.textView.becomeFirstResponder()
        
        // 设置长度label
        lengthTipLabel.text = "\(maxOfStatusLength)"
        lengthTipLabel.textColor = UIColor.lightGray
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 如果没有显示图片选择器才弹键盘
        if photoSelectorBottomCons?.constant != 0 {
            // 主动弹出键盘
            self.textView.becomeFirstResponder()
        }
    }
    
    func keyboardWillChangeFrame(nofitication: NSNotification) -> Void {
//        print("键盘改变: \(nofitication)")
        
        // UIKeyboardFrameEndUserInfoKey
        // UIKeyboardAnimationDurationUserInfoKey
        let endFrameObject = nofitication.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject
        let endFrame = endFrameObject.cgRectValue!
        
        let durationObject = nofitication.userInfo![UIKeyboardAnimationDurationUserInfoKey]! as AnyObject
        let duration = durationObject.doubleValue!
        
        print("endFrame: \(endFrame)")
        print("duration: \(duration)")
        
        let bottom = (UIScreen.height - endFrame.origin.y)
        
        self.toolBarBottomCons.constant = bottom
        
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    deinit {
        // 移除监听
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 设置照片选择器
    private func setupPhotoSelector() {
        let photoSelectorView = photoSelectorVC.view!
        // 注意: 当一个控制器的view成为另一个控制器的View的子view,这2个控制器也必须为父子关系,如果不处理,modal出来后,这个view会跑掉,屏幕旋转事件监听不到
        self.view.insertSubview(photoSelectorView, belowSubview: toolBar)
        self.addChildViewController(photoSelectorVC)
        
        // 添加约束
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0))
        self.view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0))
        let height = UIScreen.height * 0.6
        
        photoSelectorBottomCons = NSLayoutConstraint(item: photoSelectorView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: height)
        self.view.addConstraint(photoSelectorBottomCons!)
        
        self.view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: .height, relatedBy: .equal, toItem: self.view, attribute: .height, multiplier: 0.6, constant: 0))
    }
    
    private func setupToolBar() {
        // 每个item对应的图片名称
        let itemSettings = [
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        var items = [UIBarButtonItem]()
        
        for (index, dict) in itemSettings.enumerated() {
            let imageName = dict["imageName"]!
            let highLightedImageName = imageName + "_highlighted"
            
            // 获取点击事件
            let action = dict["action"]!
            
            let button = UIButton()
            button.setImage(UIImage(named: imageName), for: .normal)
            button.setImage(UIImage(named: highLightedImageName), for: .highlighted)
            button.sizeToFit()
            
            button.tag = index
            // 将字符串转成一个Selector: Selector(action)
            button.addTarget(self, action: Selector(action), for: .touchUpInside)
            
            let item = UIBarButtonItem(customView: button)
            
            items.append(item)
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        // 移除弹簧
        items.removeLast()
        toolBar.items = items
    }
    
    func picture() -> Void {
        // 修改底部约束为0
        photoSelectorBottomCons?.constant = 0
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
        
        // 键盘要下去
        textView.resignFirstResponder()
    }
    
    func trend() -> Void {
        print("#")
    }
    
    func mention() -> Void {
        print("@")
    }
    
    func emoticon(_ button: UIButton) -> Void {
        // 切换键盘,设置inputView并不会立马切换键盘
        // 在键盘弹出前 inputView == nil, 就弹出系统键盘, inputView != nil,就弹出自定义的键盘
        
        // 1.先退回键盘
        textView.resignFirstResponder()
        
        var imageName: String = ""
        // 2.设置键盘
        if textView.inputView == nil {
            textView.inputView = emoticonKeyboardView
            
            imageName = "compose_keyboardbutton_background"
        } else {
            textView.inputView = nil
            
            imageName = "compose_emoticonbutton_background"
        }
        
        button.setImage(UIImage(named: imageName), for: .normal)
        button.setImage(UIImage(named: imageName + "_highlighted"), for: .highlighted)
        
        // 3.再弹出键盘
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
            self.textView.becomeFirstResponder()
        }
    }
    
    func add() -> Void {
        print("+")
    }
    
    func buttonDidClick(button: UIButton) -> Void {
        switch button.tag {
        case 0:
            print("图片")
            
        case 1:
            print("#")
            
        case 2:
            print("@")
            
        case 3:
            print("😀")
            
        case 4:
            print("+")

        default:
            print("呵呵")
        }
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(close))
        
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        // 注意: 按钮的不可用状态需要在包装成UIBarButtonItem后再设置
        sendButton.isEnabled = false
        
        setupNaviationTitle()
    }
    
    private func setupNaviationTitle() {
        let prefix = "发微博"
        // 用户名称
        if let name = HMUserAccountVM.shared.userAccount?.screen_name {
            let text = prefix + "\n" + name // 发微博\n传智iOS
            
            let label = UILabel()
            label.font = UIFont.systemFont(ofSize: 16)
            label.textColor = UIColor.black
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.center
            
            let range = (text as NSString).range(of: name)
            
            // 属性文本
            let attr = NSMutableAttributedString(string: text)
            attr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.lightGray], range: range)
            
            label.attributedText = attr
            label.sizeToFit()
            
            navigationItem.titleView = label
            
        } else {
            navigationItem.title = prefix
        }
    }

    func close() -> Void {
        SVProgressHUD.dismiss()
        // 先关闭键盘
        self.textView.resignFirstResponder()
//        self.textView.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 发布微博
    func sendStatus() -> Void {
        let status = textView.emoticonNameText()
        
        // 判断微博的程度
        if status.characters.count > maxOfStatusLength {
            SVProgressHUD.showInfo(withStatus: "亲,您的文采太好,超出长度")
            return
        }
        
        SVProgressHUD.show(withStatus: "正在发布微博...")
        
        // 获取用户选择的图片
        let image = photoSelectorVC.photos.first
        
        HMHMStatusListVM.shared.sendStatus(status: status, image: image) { (error) in
            if error != nil {
                print("发布微博失败了: \(error)")
                SVProgressHUD.showError(withStatus: "发布微博失败了")
                return
            }
            
            // 发布微博成功了
            // 显示发布微博成功了
            SVProgressHUD.showSuccess(withStatus: "发布微博成功了")
            
            // 2秒后关闭控制器
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: { 
                self.close()
            })
        }
    }

    // MARK: - 懒加载
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
        
        // 设置按钮
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        
        button.setTitle("发布", for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .normal)
        button.bounds = CGRect(x: 0, y: 0, width: 50, height: 35)
        
        button.addTarget(self, action: #selector(sendStatus), for: .touchUpInside)
//        button.sizeToFit()
        
        return button
    }()
    
    /// 自定义键盘
    private lazy var emoticonKeyboardView: HMEmoticonKeyboardView = {
        let view = HMEmoticonKeyboardView.emoticonKeyboardView()
        
        // 设置textView
        view.textView = self.textView
        
        return view
    }()
    
    /// 图片选择器的控制器
    private lazy var photoSelectorVC: HMPhotoSelectorController = HMPhotoSelectorController()
}

extension HMComposeViewController: UITextViewDelegate {
    // 文字改变调用这个方法
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText
        
        // 获取textView现有文本的长度
        let length = textView.emoticonNameText().characters.count
        // 计算文字剩余长度
        let leftLength = maxOfStatusLength - length
        
        lengthTipLabel.text = "\(leftLength)"   // [呵呵]
        lengthTipLabel.textColor = leftLength < 0 ? UIColor.red : UIColor.lightGray
    }
}
